/**************************************************************************************************************
 * @copyright Copyright (c) 2015—2024 Uniorange Internet Design Co., LTD. All rights reserved.
 * @author Uniorange Internet Design Co., LTD.
 *
 * This file is part of the App project. Copyright © Uniorange Internet Design Co., Ltd. All Rights Reserved.
 * Unauthorized copying of this file, via any medium is strictly prohibited Proprietary and confidential.
 *
 **************************************************************************************************************/
package com.jinyu.servicedemo.client;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelId;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 邱金波
 * @version V0.1
 * @className NettyClient
 * @description 客户端
 * @date 2024/09/14 14:33
 */
@Data
@Slf4j
public class NettyClient {
    private static Map<ChannelId, NettyClient> nettyClientMap;
    public Bootstrap bootstrap;

    static {
        nettyClientMap = new ConcurrentHashMap<>();
    }

    //只有链接操作成功才会将client加入到本地缓存中
    private ChannelId channelId;
    private String remoteIp;
    private int remotePort;
    private String name;

    public NettyClient(ChannelId channelId, String remoteIp, int remotePort) {
        this.channelId = channelId;
        this.remoteIp = remoteIp;
        this.remotePort = remotePort;
    }

    public NettyClient(Bootstrap bootstrap, String remoteIp, int remotePort) {
        this.remoteIp = remoteIp;
        this.remotePort = remotePort;
        this.bootstrap = bootstrap;
    }

    public static void addNettyClient(NettyClient nettyClient) {
        nettyClientMap.put(nettyClient.channelId, nettyClient);
    }

    public static NettyClient getNettyClient(ChannelId channelId) {
        return nettyClientMap.get(channelId);
    }

    public static void removeNettyClient(ChannelId channelId) {
        nettyClientMap.remove(channelId);
    }

    /**
     * 客户端通用connect方法
     * TODO: 是否需要同步？
     *
     * @param host
     * @param port
     */
    synchronized
    public void connect(String host, int port) {
        bootstrap.connect(host, port);
    }
}
